﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgNetComponentsDx.Browsers;
using BuildHelper.Work.Tools.DataSets;
using ProgNetComponents.Classes;

namespace BuildHelper.Work.Tools
{
    public partial class GeneratorForm : XtraForm
    {
        public GeneratorForm()
        {
            InitializeComponent();
            splitContainerControl9.SplitterPositionChanged += new EventHandler(splitContainerControl9_SplitterPositionChanged);
        }

        void splitContainerControl9_SplitterPositionChanged(object sender, EventArgs e)
        {
            
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsDesignMode())
            {
                lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
                lueBranczAdditionalColumnInfo.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
                Setup.Brancze.BranczeTools.ActiveBranchChanged += new EventHandler(BranczeTools_ActiveBranchChanged);
                xtraTabControl1.SetTabMinSize(150);
            }
        }

        void splitContainerControl4_SplitterPositionChanged(object sender, EventArgs e)
        {
           
        }

        void BranczeTools_ActiveBranchChanged(object sender, EventArgs e)
        {
            lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
            lueBranczAdditionalColumnInfo.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
        }

        #region Table Create / Alter
        private string TableName
        {
            get { return teTableName.Text.AsString().Trim(); }
        }
        private class TableData
        {
            public string Sequence
            {
                get;
                set;
            }
            public string MainSql
            {
                get;
                set;
            }
            public string RefConstraints
            {
                get;
                set;
            }
            public string CheckConstraints
            {
                get;
                set;
            }
            public string Comments
            {
                get;
                set;
            }
            public string SetupState
            {
                get;
                set;
            }
            public string AuditTrail
            {
                get;
                set;
            }
            public string AdditionalColumnInfo
            {
                get;
                set;
            }
        }
        
        private TableData GetTableData(bool create)
        {
            string table = teTableName.Text.AsString().Trim();
            TableData dt = new TableData();
            string mainSql = "";
            string auditTrail = "";
            string auditTrailRels = "";
            this.createTableDataSet.TABLE_COLUMNS.Trim("NAME", "DEFAULT", "COMMENT", "REF_TO_TABLE", "REF_TO_COLUMN");
            this.createTableDataSet.CHOICE.Trim("CH_VALUE", "CH_COMMENT");

            DataRow[] rows = this.createTableDataSet.TABLE_COLUMNS.Select(null, "POS", DataViewRowState.CurrentRows);
            string col = "";
            if (create)
            {
                dt.Sequence = "CREATE SEQUENCE SEQ_" + table + "_RECID START WITH 1 INCREMENT BY 1 NOCYCLE;";
                mainSql = "CREATE TABLE " + table;
                resManControlTable.AppendText(table, teTableResMan.Text);
                if (ceAuditTrail.Checked)
                {
                    bool added = false;
                   
                    foreach (DataRow r in rows)
                    {
                        col = r["NAME"].AsString().Trim();
                        if (col.EndsWith("_CODE"))
                        {
                            auditTrail = auditTrail.AppendLine("update_ga_audflds_temporarry('" + table + "', '" + col + "', NULL, NULL, NULL, NULL, NULL, 'N', NULL, NULL, NULL);");
                            added = true;
                            break;
                        }
                    }
                    if (!added)
                    {
                        auditTrail = auditTrail.AppendLine("--update_ga_audflds_temporarry('" + table + "', 'UNIQUE_KEY', NULL, NULL, NULL, NULL, NULL, 'N', NULL, NULL, NULL);");
                    }
                }
            }
            else
            {
                mainSql = "ALTER TABLE " + table + " ADD ";
            }
            #region columns
           
            string cols = "";
            string pk = "";
            string refs = "";
            string checks = "";
            DataRow[] children;
            string comment = "";
            if (teComment.Text.IsNotNull() && create)
                comment = "COMMENT ON TABLE " + table + " IS " + teComment.Text.AsString().EscapeSql() + ";";
            string colComment = "";
            string checkConst = "";
            string prefix = "";
            int kolNo = 0;
            foreach (DataRow r in rows)
            {
                checkConst = "";
                col = r["NAME"].AsString().Trim();
                if (kolNo == 0)
                    prefix = col;
                else
                    prefix = col.GetCommonPrefix(prefix);
                kolNo++;
                if (ceAuditTrail.Checked)
                {
                    auditTrail = auditTrail.AppendLine("update_ga_audflds_temporarry('" + col + "', NULL , NULL, NULL, NULL, NULL, NULL, 'N', NULL, NULL, NULL);");
                }
                if (r["COMMENT"].IsNotNull())
                    colComment = r["COMMENT"].AsString().Trim();
                cols = cols.AppendString("," + Constants.NewLineLinux);
                cols += "\t" + col + " " + r["TYPE"].AsString();
                if (r["SIZE"].IsNotNull() && r["TYPE"].AsString() == "VARCHAR2")
                    cols += "(" + r["SIZE"] + ")";
                if (r["DEFAULT"].IsNotNull())
                    cols += " DEFAULT " + (r["DEFAULT"].AsInt(-1) != -1 ? r["DEFAULT"].AsString() : r["DEFAULT"].AsString().EscapeSql());
                
                if (r["NULLABLE"].AsBool() == false)
                    cols += " NOT NULL";
                if (r["PK"].AsBool())
                    pk = pk.AppendString(", ") + col;
                if (r["REF_TO_TABLE"].IsNotNull())
                {
                    refs = refs.AppendLine("ALTER TABLE " + table + " ADD CONSTRAINT" + Constants.NewLineLinux +
                        "\t\t" + col + "_FK FOREIGN KEY (" + col + ") REFERENCES " + r["REF_TO_TABLE"] + "(" + r["REF_TO_COLUMN"] + ")" +
                        (r["DEL_CASCADE"].AsBool() ? " ON DELETE CASCADE;" : ";"));
                    if (ceAuditTrail.Checked && r["DEL_CASCADE"].AsBool())
                    {
                        auditTrailRels = auditTrailRels.AppendLine("update_ga_audrels_temporarry('" + col + "_FK', '" + r["REF_TO_TABLE"] + "', '" + r["REF_TO_COLUMN"] + "', '" + table + "', '" + col + "', NULL, NULL, NULL);");
                    }
                }
                children = r.GetChildRows("FK_TABLE_COLUMNS_CHOICE");
                if (children != null && children.Length > 0)
                {
                    foreach (DataRow c in children)
                    {
                        if (c.CanRead())
                        {
                            if (c["CH_COMMENT"].IsNotNull())
                                colComment = colComment.AppendLine(c["CH_VALUE"].AsString() + " - " + c["CH_COMMENT"]);
                            checkConst = checkConst.AppendString(",") + c["CH_VALUE"].AsString().EscapeSql();
                        }
                    }
                   
                    if (checkConst.IsNotNull())
                    {
                        checkConst = "ALTER TABLE " + table + " ADD CONSTRAINT" + Constants.NewLineLinux +
                            "\t\t" + col + "_CH CHECK (" + r["NAME"].AsString() + " IN (" + checkConst + "));";
                        checks = checks.AppendLine(checkConst);
                    }
                }
                if (colComment.IsNotNull())
                    comment = comment.AppendLine("COMMENT ON COLUMN " + table + "." + col + " IS " + colComment.EscapeSql() + ";");

                if (r["COMMENT"].IsNotNull())
                {
                    resManControlTable.AppendText(r["NAME"].AsString(), r["COMMENT"].AsString());
                }
            }
            if (create && ceDodajKolumnySetupowe.Checked)
            {
                if (prefix.IsNotNull())
                {
                    col = prefix + "CREATEDBY";
                    cols = cols.AppendString("," + Constants.NewLineLinux);
                    cols += "\t" + col + " VARCHAR2(50)";
                    comment = comment.AppendLine("COMMENT ON COLUMN " + table + "." + col + " IS 'User who created the record';");

                    col = prefix + "CREATEDDT";
                    cols = cols.AppendString("," + Constants.NewLineLinux);
                    cols += "\t" + col + " DATE";
                    comment = comment.AppendLine("COMMENT ON COLUMN " + table + "." + col + " IS 'Date when record was created';");

                    col = prefix + "CREATEDENV";
                    cols = cols.AppendString("," + Constants.NewLineLinux);
                    cols += "\t" + col + " VARCHAR(50)";
                    comment = comment.AppendLine("COMMENT ON COLUMN " + table + "." + col + " IS 'Environment from which the record was created';");

                    col = prefix + "UPDATEDBY";
                    cols = cols.AppendString("," + Constants.NewLineLinux);
                    cols += "\t" + col + " VARCHAR2(50)";
                    comment = comment.AppendLine("COMMENT ON COLUMN " + table + "." + col + " IS 'User who updated the record';");

                    col = prefix + "UPDATEDDT";
                    cols = cols.AppendString("," + Constants.NewLineLinux);
                    cols += "\t" + col + " DATE";
                    comment = comment.AppendLine("COMMENT ON COLUMN " + table + "." + col + " IS 'Date when record was updated';");

                    col = prefix + "UPDATEDENV";
                    cols = cols.AppendString("," + Constants.NewLineLinux);
                    cols += "\t" + col + " VARCHAR(50)";
                    comment = comment.AppendLine("COMMENT ON COLUMN " + table + "." + col + " IS 'Environment from which the record was updated';");
                }
            }
            #endregion

            mainSql += " (" + Constants.NewLineLinux + cols;
            if (pk.IsNotNull())
                mainSql += "," + Constants.NewLineLinux + "\t CONSTRAINT " + table + "_PK PRIMARY KEY (" + pk + ") " + Constants.NewLineLinux;

            mainSql += Constants.NewLineLinux + ");";

            dt.RefConstraints = refs;
            dt.CheckConstraints = checks;
            dt.MainSql = mainSql;
            
            dt.Comments = comment;
            dt.AuditTrail = auditTrail;
            if (auditTrail.IsNotNull() && auditTrailRels.IsNotNull())
                dt.AuditTrail += Constants.NewLineLinux;
            dt.AuditTrail += auditTrailRels;

            if (ceTableSetupStateTrigger.Checked)
            {
                dt.SetupState = "CREATE OR REPLACE TRIGGER INS_UPD_"+table + Constants.NewLineLinux +
                                "AFTER UPDATE OR INSERT OR DELETE" + Constants.NewLineLinux +
                                "ON " + table + Constants.NewLineLinux +
                                "BEGIN" + Constants.NewLineLinux +
                                "GCM_UPDATE_SETUP_STAT_MODCOUNT('" + table + "');" + Constants.NewLineLinux +
                                "END;" + Constants.NewLineLinux +
                                "/" + Constants.NewLineLinux +
                                Constants.NewLineLinux +
                                "UPDATE_SETUP_STATE('" + table + "');";
            }
            if (create && ceAdditionalInfoColumns.Checked && prefix.IsNotNull())
            {
                dt.AdditionalColumnInfo = "                case " + table.AddDoubleQuotes() + @":
                    columnPrefix = " + prefix.AddDoubleQuotes() + @";
                    break;"; ;
            }
            return dt;
        }

        private void CreateScripts(bool create)
        {
            string str = "";
            resManControlTable.Text = "";
            if (!modeProvider1.ValidateRequiredColumns(gvTableDefColumns, ref str))
            {
                if (str.IsNull())
                    str = "Błąd walidacji.";
                this.ShowErrorDialog(str);
                return;
            }
            TableData td = GetTableData(create);
            meTableSql.Text = "";
            if (td.Sequence.IsNotNull())
                meTableSql.AppendText(td.Sequence + Constants.NewLineLinux + Constants.NewLineLinux);
            meTableSql.AppendText(td.MainSql + Constants.NewLineLinux + Constants.NewLineLinux);
            if (td.CheckConstraints.IsNotNull())
                meTableSql.AppendText(td.CheckConstraints + Constants.NewLineLinux + Constants.NewLineLinux);
            if (td.RefConstraints.IsNotNull())
                meTableSql.AppendText(td.RefConstraints + Constants.NewLineLinux + Constants.NewLineLinux);
            if (td.Comments.IsNotNull())
                meTableSql.AppendText(td.Comments + Constants.NewLineLinux + Constants.NewLineLinux);
            if (td.SetupState.IsNotNull())
                meTableSql.AppendText(td.SetupState + Constants.NewLineLinux + Constants.NewLineLinux);
            if (td.AuditTrail.IsNotNull())
                meTableSql.AppendText(td.AuditTrail + Constants.NewLineLinux + Constants.NewLineLinux);
            meAdditionalInfoColumns.Text = td.AdditionalColumnInfo;
        }
        private void btnTworzenie_Click(object sender, EventArgs e)
        {
            CreateScripts(true);
        }
        
        private void btnAlter_Click(object sender, EventArgs e)
        {
            CreateScripts(false);
        }
        private void btnCopyTableSql_Click(object sender, EventArgs e)
        {
            Copy(meTableSql);
        }

        
        #endregion

        #region Common Tools
        private void Copy(MemoEdit memo)
        {
            Clipboard.SetText(memo.Text);
        }
        #endregion
        #region opcje

        private void btnOpcjeSql_Click(object sender, EventArgs e)
        {
            Copy(meOpcjeSql);
        }

        private void btnOpcjeGeneruj_Click(object sender, EventArgs e)
        {
            createTableDataSet.OPCJE.Trim("KOD", "NAZWA","DEFAULT");
            DataRow[] rows = createTableDataSet.OPCJE.Select();
            string insert = "";
            string update = "";
            resManControlOpcje.Text = "";

            string systemy = "";
            string releaseNote = "";
            string opCode = "";
            string opName = "";
            string opLocalization = "";
            string opSystems = "";
            string sysName = "";
            DataTable dt = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.Apps);
            DataRow brRow;
            foreach (DataRow r in rows)
            {
                opCode = r["KOD"].AsString();
                opName = r["NAZWA"].AsString();
                opLocalization = r["LOKALIZACJA"].AsString();

                insert = insert.AppendLine("INSERT INTO ga_config_names(code, name, location) VALUES( " + opCode.EscapeSql() + ", " + opName.EscapeSql() + ", " + opLocalization.EscapeSql() + ");");
                systemy = r["SYSTEMY"].AsString();
                resManControlOpcje.AppendText(opCode, opName);
                opSystems = "";
                int last = systemy.Length - 1;
                int i = 0;
                foreach (char c in systemy)
                {
                    update = update.AppendLine("update_configs(" + opCode.EscapeSql() + ", '" + c + "', " + r["DEFAULT"].AsString().EscapeSql() + ", '', '', '" + r["TAB"] + "' );");
                    if (ceReleaseNotes.Checked)
                    {
                        sysName = "" + c;
                        brRow = dt.SelectFirstRow("STP_APP_GENE_LETTER = '" + c + "'");
                        if (brRow != null && brRow["STP_APP_GENE_NAZWA"].IsNotNull())
                            sysName = brRow["STP_APP_GENE_NAZWA"].AsString();
                        else
                            FormMain.ShowWarningAlert("Brak nazwy systemu dla litery " + c);

                        if(i== last)
                            opSystems = opSystems.AppendString(" and ") + sysName;
                        else
                            opSystems = opSystems.AppendString(", ") + sysName;
                    }
                    i++;
                }
                if (ceReleaseNotes.Checked)
                {
                    releaseNote = releaseNote.AppendLine("In " + opSystems + " Option setup, on " + opLocalization + " tab, " +
                        " the system provides new option " + opName.PutBetween("'") + " (" + opCode + ").");
                }
                update += Constants.NewLineLinux;
            }

            meOpcjeSql.Text = insert + Constants.NewLineLinux +
                Constants.NewLineLinux + update;
            

            meReleaseNotes.Text = releaseNote;

            Setup.OptionsTabs.OptionsTabsForm.UpdateLocalizations();
        }

        #endregion

        private void btnTableDataSet_Click(object sender, EventArgs e)
        {
            GetXmlDef();
        }
        private string GetXmlDef()
        {
            string xml = "";
            StringBuilder strBuilder = new StringBuilder();
            string pk = "";

            strBuilder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            strBuilder.AppendLine("<xs:schema id=\"NewDataSet\" xmlns=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:msprop=\"urn:schemas-microsoft-com:xml-msprop\">");
            strBuilder.AppendLine("  <xs:annotation>");
            strBuilder.AppendLine("    <xs:appinfo source=\"urn:schemas-microsoft-com:xml-msdatasource\">");
            strBuilder.AppendLine("      <DataSource DefaultConnectionIndex=\"0\" FunctionsComponentName=\"QueriesTableAdapter\" Modifier=\"AutoLayout, AnsiClass, Class, Public\" SchemaSerializationMode=\"IncludeSchema\" xmlns=\"urn:schemas-microsoft-com:xml-msdatasource\">");
            strBuilder.AppendLine("        <ConnectionRefs />");
            strBuilder.AppendLine("        <Connections />");
            strBuilder.AppendLine("        <TableRefs>");
            strBuilder.AppendLine("          <DesignTableRef Name=" + TableName.AddDoubleQuotes() + ">");
            strBuilder.AppendLine("            <ColumnRefs />");
            strBuilder.AppendLine("            <SourceRefs />");
            strBuilder.AppendLine("          </DesignTableRef>");
            strBuilder.AppendLine("        </TableRefs>");
            strBuilder.AppendLine("        <Tables />");
            strBuilder.AppendLine("        <RelationRefs />");
            strBuilder.AppendLine("        <SourceRefs />");
            strBuilder.AppendLine("        <Sources />");
            strBuilder.AppendLine("      </DataSource>");
            strBuilder.AppendLine("    </xs:appinfo>");
            strBuilder.AppendLine("  </xs:annotation>");
            strBuilder.AppendLine("  <xs:element name=\"NewDataSet\" msdata:IsDataSet=\"true\" msdata:UseCurrentLocale=\"true\" msprop:Generator_UserDSName=\"NewDataSet\" msprop:Generator_DataSetName=\"NewDataSet\">");
            strBuilder.AppendLine("    <xs:complexType>");
            strBuilder.AppendLine("      <xs:choice minOccurs=\"0\" maxOccurs=\"unbounded\">");
            strBuilder.AppendLine("        <xs:element name=" + TableName.AddDoubleQuotes() +
                " msprop:Generator_TableClassName=\"" + TableName + "DataTable\" msprop:Generator_TableVarName=\"table" + TableName +
                "\" msprop:Generator_TablePropName=" + TableName.AddDoubleQuotes() +
                    " msprop:Generator_RowDeletingName=\"" + TableName + "RowDeleting\" msprop:Generator_UserTableName=\"" +
                    TableName + "\" msprop:Generator_RowChangingName=\"" + TableName +
                        "RowChanging\" msprop:Generator_RowEvHandlerName=\"" + TableName + "RowChangeEventHandler\" msprop:Generator_RowDeletedName=\"" + TableName +
                        "RowDeleted\" msprop:Generator_RowEvArgName=\"" + TableName +
                        "RowChangeEvent\" msprop:Generator_RowChangedName=\"" + TableName +
                        "RowChanged\" msprop:Generator_RowClassName=\"" + TableName + "Row\">");

            strBuilder.AppendLine("          <xs:complexType>");
            strBuilder.AppendLine("            <xs:sequence>");
            DataRow[] rows = this.createTableDataSet.TABLE_COLUMNS.Select();
            string colStr = "";
            string type = "";
            string nType = "";
            string colName = "";
            foreach (DataRow r in rows)
            {
                colName = r["NAME"].AsString().Trim();
                colStr = "              <xs:element name=\"" + colName + "\"";
                type = r["TYPE"].AsString();

                if (r["PK"].AsBool())
                {
                    if(type == "NUMBER")
                        colStr += " msdata:AutoIncrement=\"true\" msdata:AutoIncrementSeed=\"-1\" msdata:AutoIncrementStep=\"-1\" ";
                    pk =
                    "    <xs:unique name=\"" + TableName + "_PK\" msdata:PrimaryKey=\"true\">" + Constants.NewLineLinux +
                    "      <xs:selector xpath=\".//" + TableName + "\" />" + Constants.NewLineLinux +
                    "      <xs:field xpath=\"" + colName + "\" />" + Constants.NewLineLinux +
                    "    </xs:unique>";
                }
                colStr += " msprop:Generator_ColumnVarNameInTable=\"column" + colName +
                    "\" msprop:Generator_ColumnPropNameInRow=\"" + colName +
                    "\" msprop:Generator_ColumnPropNameInTable=\"" + colName +
                    "Column\" msprop:Generator_UserColumnName=\"" + colName + "\" type=\"xs:";

                switch (type)
                {
                    case "NUMBER":
                        nType = "decimal";
                        break;
                    case "VARCHAR2":
                        nType = "string";
                        break;
                    case "DATE":
                        nType = "dateTime";
                        break;
                    case "BLOB":
                    case "CLOB":
                        nType = "base64Binary";
                        break;
                    default:
                        nType = "string";
                        break;
                }
                colStr += nType + "\"";
                if (r["DEFAULT"].IsNotNull())
                    colStr += " default=\"" + r["DEFAULT"] + "\"";
                if(!r["PK"].AsBool())
                    colStr+= " minOccurs=\"0\"";
                colStr += " />";
                strBuilder.AppendLine(colStr);
            }
            strBuilder.AppendLine("            </xs:sequence>");
            strBuilder.AppendLine("          </xs:complexType>");
            strBuilder.AppendLine("        </xs:element>");
            strBuilder.AppendLine("      </xs:choice>");
            strBuilder.AppendLine("    </xs:complexType>");
            if (pk.IsNotNull())
            {
                strBuilder.AppendLine(pk);
            }
            strBuilder.AppendLine("  </xs:element>");
            strBuilder.AppendLine("</xs:schema>");
            xml = strBuilder.ToString().Trim();
            DataObject o = new DataObject();
            o.SetData("CF_PROJITEM", "");
            o.SetData("System.String", xml);
            o.SetData("UnicodeText", xml);
            o.SetData("Text", xml);
            o.SetData("CF_DSI", xml);
            o.SetData("CF_DSI_CONTENT_TYPE", "AllOtherCases");

            Clipboard.SetDataObject(o, true);
            this.ShowDxInfoDialog("Xml zapisany w schowku");
            return xml;
        }

        #region ResMan/Const
        string className;
        string orgClassName;
        private void btnGenResMan_Click(object sender, EventArgs e)
        {
            createTableDataSet.RESMAN.Trim("KOD");
            DataRow[] rows = createTableDataSet.RESMAN.Select();
            resManControlResMan.Text = "";
            string constants = "";
            bool genConst = teConstClassName.EditValue.IsNotNull();
            string browser = "";
            orgClassName = teConstClassName.Text.AsString();
            className = ProgNetComponents.Tools.ConstHelper.GetFriendlyName(orgClassName);
            string constName;
            foreach (DataRow r in rows)
            {
                resManControlResMan.AppendText(r["KOD"].AsString(), r["WARTOSC"].AsString());
                constName = ProgNetComponents.Tools.ConstHelper.GetFriendlyName(r["WARTOSC"].AsString());
                if (genConst)
                {
                    constants = constants.AppendLine("\tpublic const string " + constName + " = " + r["CONST"].AsString().AddDoubleQuotes() + ";");
                }
                if (ceConstBrowser.Checked && genConst)
                {
                    browser = browser.AppendLine("dt" + className + ".Rows.Add(GcmGlobals." + className + "." + constName + ", GcmResMan.ResMgr.GetString(" + r["KOD"].AsString().AddDoubleQuotes() + "));");
                }
            }
            if (constants.IsNotNull() && teConstClassName.Text.IsNotNull())
            {
                constants = "public static class " + className + Constants.NewLineLinux +
                    "{" + Constants.NewLineLinux +
                    constants + Constants.NewLineLinux +
                    "}";
            }
            meResConstClass.Text = "";
            meBrowser.Text = "";

            meResConstClass.Text += constants;
            if (browser.IsNotNull())
            {
                browser = "DataTable dt" + className + " = new DataTable(" + className.AddDoubleQuotes() + ");" + Constants.NewLineLinux +
                    "dt" + className + ".Columns.Add(\"CODE\");" + Constants.NewLineLinux +
                    "dt" + className + ".Columns.Add(\"NAME\");" + Constants.NewLineLinux + Constants.NewLineLinux +
                    browser + Constants.NewLineLinux + Constants.NewLineLinux +
                    "IBrowserDataProvider " + className + "Provider = BrowserDataProviderFactory.Instance.CreateDataProvider(dt" + className + ", \"CODE\", \"NAME\");";
                meBrowser.Text = browser;
            }
        }

        #endregion

        private void btnClear_Click(object sender, EventArgs e)
        {
            meAdditionalInfoColumns.Text = string.Empty;
            teTableName.EditValue = "";
            teComment.EditValue = "";
            teTableResMan.EditValue = "";
            ceTableSetupStateTrigger.Checked = false;
            ceAuditTrail.Checked = true;
            ceAdditionalInfoColumns.Checked = true;
            ceDodajKolumnySetupowe.Checked = true;
            meTableSql.Text = "";
            resManControlTable.Text = "";
            createTableDataSet.CHOICE.Clear();
            createTableDataSet.TABLE_COLUMNS.Clear();
        }

        private void btnczyscOpcje_Click(object sender, EventArgs e)
        {
            meOpcjeSql.Text = "";
            resManControlOpcje.Text = "";
            meReleaseNotes.Text = "";
            createTableDataSet.OPCJE.Clear();
        }

        private void btnCzyscResMan_Click(object sender, EventArgs e)
        {
            resManControlResMan.Text = "";
            ceConstBrowser.Checked = false;
            teConstClassName.EditValue = "";
            createTableDataSet.RESMAN.Clear();
            meBrowser.Text = "";
            meResConstClass.Text = "";
        }

        private void modeProvider1_CustomGetModes(object sender, ProgNetComponentsDx.Mode.CustomModeSettingsEventArgs e)
        {
            if (e.Row != null)
            {
                if (sender == colSIZE)
                {
                    e.IsRequired = e.Row["TYPE"].AsString() == "VARCHAR2";
                    e.IsReadOnly = !e.IsRequired;
                }
                if (sender == colREF_TO_TABLE)
                {
                    e.IsRequired = e.Row["REF_TO_COLUMN"].IsNotNull();
                }
                if (sender == colREF_TO_COLUMN)
                {
                    e.IsRequired = e.Row["REF_TO_TABLE"].IsNotNull();
                }
            }
        }

        private void btnCopyReleaseNotes_Click(object sender, EventArgs e)
        {
            Copy(meReleaseNotes);
        }

        private void btnAddYNCheck_Click(object sender, EventArgs e)
        {
            DataRow r = gvTableDefColumns.GetFocusedDataRow();
            if (r != null)
            {
                DataRow[] children = r.GetChildRows("FK_TABLE_COLUMNS_CHOICE");
                if (children == null || children.Length == 0)
                {
                    createTableDataSet.CHOICE.AddCHOICERow(r as CreateTableDataSet.TABLE_COLUMNSRow, "Y", "");
                    createTableDataSet.CHOICE.AddCHOICERow(r as CreateTableDataSet.TABLE_COLUMNSRow, "N", "");
                }
            }
        }

        private void gvTableDefColumns_KeyDown(object sender, KeyEventArgs e)
        {
            
        }

        private void btnResConst_Click(object sender, EventArgs e)
        {
            Copy(meResConstClass);
        }

        private void btnCopyBrowser_Click(object sender, EventArgs e)
        {
            Copy(meBrowser);
        }

        private void btnAddClassToGcmGlobals_Click(object sender, EventArgs e)
        {
            string brancz = lueBrancz.EditValue.AsString();
            string text = meResConstClass.Text;
            if (text.IsNullOrEmpty())
            {
                FindForm().ShowDxInfoDialog("Nie ma nic do dodania.");
                return;
            }
            text = Constants.NewLineLinux + "\t\t" + "#region " + orgClassName + Constants.NewLineLinux +
                "\t\t" + text.TrimStart().Replace(Constants.NewLineLinux, Constants.NewLineLinux + "\t\t").TrimEnd() + Constants.NewLineLinux +
                "\t\t" + "#endregion" + Constants.NewLineLinux + Constants.NewLineLinux;
           
            if (brancz.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
                if (r != null)
                {
                    string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                    string file = katalog + @"\nd_src\gene\apps\gcm\src\gui\GcmCmnTools\GcmGlobals.cs";
                    
                    if (System.IO.File.Exists(file))
                    {
                        string content = file.ReadFile();
                        if (content.XMatch("class\\s+" + className + "\\s+"))
                        {
                            this.ShowDxErrorDialog("Klasa " + className + " już istnieje.");
                            return;
                        }
                        int idx = content.GetFirstMatch("^(.*?GcmGlobals\\s*{)", 1, System.Text.RegularExpressions.RegexOptions.IgnoreCase| System.Text.RegularExpressions.RegexOptions.Singleline).Length;
                        if (idx > 0)
                        {
                            content = content.Insert(idx, text).Trim();
                            content.WriteToFile(file);
                            FormMain.ShowInfoAlert("Wpisy dodane");
                        }
                    }
                    else
                    {
                        this.ShowDxErrorDialog("Brak pliku:\n" + file);
                    }
                }
                else
                {
                    this.ShowDxErrorDialog("Nie można znaleźć brancza.");
                }
            }
            else
            {
                this.ShowDxInfoDialog("Wybierz brancza.");
            }
        }

        private void rep_TAB_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            Browser b = BrowserCache.GetBrowser(Init.InitFormBrowserNames.Setup.OptionsTabs, false);

            ObjectDialogResult dlg = b.ShowDialog();
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                string tab = dlg.Value.AsString();
                string lokalizacja = b.GetColumnValueForEditValue(tab, "STP_OPT_LOKALIZACJA").AsString();
                if (gvOpcje.IsNewItemRow(gvOpcje.FocusedRowHandle))
                    gvOpcje.AddNewRow();

                    gvOpcje.SetRowCellValue(gvOpcje.FocusedRowHandle, "TAB", tab);
                    gvOpcje.SetRowCellValue(gvOpcje.FocusedRowHandle, "LOKALIZACJA", lokalizacja);
            }
        }

        private void gvOpcje_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            DataRow r = null;
            if (e.Row != null && e.Row is DataRowView)
                r = (e.Row as DataRowView).Row;
            if (r != null)
            {
                string tab = r["TAB"].AsString();
                string lokalizacja = r["LOKALIZACJA"].AsString();
                if (tab.IsNotNull() && lokalizacja.IsNotNull())
                {
                     Browser b = BrowserCache.GetBrowser(Init.InitFormBrowserNames.Setup.OptionsTabs, false);

                     if (b.GetRowForValue(tab) == null && b.GetTable().SelectFirstRow("STP_OPT_LOKALIZACJA = " + lokalizacja.EscapeSql()) == null)
                     {
                         DataRow row = b.GetTable().NewRow();
                         row["STP_OPT_TAB"] = tab;
                         row["STP_OPT_LOKALIZACJA"] = lokalizacja;
                         b.GetTable().Rows.Add(row);
                     }
                }
            }
        }

        private void btnKopjujAdditionalInfoColumns_Click(object sender, EventArgs e)
        {
            Copy(meAdditionalInfoColumns);
        }

        private void btnDodajAdditionalInfoColumns_Click(object sender, EventArgs e)
        {
            string brancz = lueBranczAdditionalColumnInfo.EditValue.AsString();
            string text = meAdditionalInfoColumns.Text;
            if (text.IsNullOrEmpty())
            {
                this.ShowDxInfoDialog("Nie ma nic do dodania.");
                return;
            }

            if (brancz.IsNotNull())
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
                if (r != null)
                {
                    string katalog = r["STP_BR_KATALOG"].AsString().TrimEnd('\\');
                    string file = katalog + @"\nd_src\gene\apps\gcm\src\gui\GcmTools\GcmSetupAdditionalColumns\AdditionalInfoColumns.cs";

                    if (System.IO.File.Exists(file))
                    {
                        string content = file.ReadFile();
                        string mask = "(private static string getColumnPrefix\\(string tableName\\).*return columnPrefix;)";
                        string method = content.GetFirstMatch(mask, 1, System.Text.RegularExpressions.RegexOptions.Singleline);
                        if (method.IsNull())
                        {
                            this.ShowDxInfoDialog("Nie można odnależć metody getColumnPrefix");
                            return;
                        }
                        string table = text.GetFirstMatch("case \"(\\w*)\":",1, System.Text.RegularExpressions.RegexOptions.Singleline);
                        string prefix = text.GetFirstMatch("columnPrefix = \"(\\w*)\";", 1, System.Text.RegularExpressions.RegexOptions.Singleline);

                        if (method.XMatch("case " + table.AddDoubleQuotes()))
                        {
                            this.ShowDxInfoDialog("Tabela \"" + table + "\" jest już dodana.");
                            return;
                        }
                        if (method.XMatch("columnPrefix = " + prefix.AddDoubleQuotes()))
                        {
                            this.ShowDxInfoDialog("Prefix \"" + prefix + "\" jest już dodany.");
                            return;
                        }

                        string newMethod = method.XReplace("(\\s*default:)", Constants.NewLineLinux + text + "$1");
                        content = content.Replace(method, newMethod);
                        content.WriteToFile(file);
                        FormMain.ShowInfoAlert("Wpisy dodane");
                    }
                    else
                    {
                        this.ShowDxErrorDialog("Brak pliku:\n" + file);
                    }
                }
                else
                {
                    this.ShowDxErrorDialog("Nie można znaleźć brancza.");
                }
            }
            else
            {
                this.ShowDxInfoDialog("Wybierz brancza.");
            }
        }
    }
}
